package com.thjk.bdf.preloan.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.thjk.bdf.common.base.BasicResp;
import com.thjk.bdf.common.constants.ResidsConstant;
import com.thjk.bdf.common.enmus.LoanEnum;
import com.thjk.bdf.common.enmus.ProductEnum;
import com.thjk.bdf.common.enmus.ServiceEnum;
import com.thjk.bdf.common.entity.SmsLog;
import com.thjk.bdf.common.utils.DateUtils;
import com.thjk.bdf.common.utils.GenerateIdsUtil;
import com.thjk.bdf.common.utils.RedisUtils;
import com.thjk.bdf.preloan.service.config.AppConfig;
import com.thjk.bdf.preloan.service.config.LoanConfig;
import com.thjk.bdf.preloan.service.repository.dao.SmsLogMapper;
import com.thjk.bdf.service.SmsService;

/**
 * 
 * @创建日期： 2019年11月4日
 * @author 束凯
 * @Description：验证码处理类；包括发送，验证，次数验证
 */
@RestController
@RequestMapping("/sms")
public class SmsServiceImpl implements SmsService{
	
	private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

	@Value("${LN1014.url}")
	private String sendSmsUrl;// 发送短信地址
	
	@Value("${sms.templete.code}")
	private String templeteCode;//短信模板
	
	@Value("${sms.warn.phone}")
	private Integer warnPhone;//手机单日上限
	
	@Value("${sms.warn.ip}")
	private Integer warnIp;//同一wifi地址上限
	
	@Value("${sms.warn.wifi}")//ip地址上限
	private Integer warnWifi;
	
	@Value("${sms.code.expires}")
	private Long smsExpires; 
	/**
	 * 默认短信验证码 
	 * 默认：111111
	 */
	@Value("${defaul.sms.code}")
	private String defaultSmsCode;
	
	@Autowired
    private AppConfig appConfig;
	
	@Autowired
    private LoanConfig loanConfig;
	
	@Autowired
    private RestTemplate restTemplate;
	
	@Autowired
	private SmsLogMapper smsLogMapper;
	
	@Autowired
	private RedisUtils redisUtils;
	
	private static final String TRANCODE_LN1014 = "LN1014";
	
	@Override
	@RequestMapping(value = "/sendSmsMsg" , method = RequestMethod.POST)
	public BasicResp sendSmsMsg(@RequestBody SmsLog smsLog) {
		
		Map<String, Object> params = new HashMap<>();
		//验证码
		String smsVfCode = GenerateIdsUtil.getVerSmsCode();
		
		params.put("TranDate", DateUtils.formatDate("yyyyMMddHHmmss")); //交易日期
		params.put("SeriNo", GenerateIdsUtil.generateId(appConfig.getAppIp())); //交易唯一标识
		params.put("SysCode", loanConfig.getSysCode()); //系统标识/产品代码
		params.put("ChanId", loanConfig.getChanlId()); //渠道 01-PC 02-APP
		params.put("TranCode", TRANCODE_LN1014); //交易编码
		params.put("Product", loanConfig.getProductCode()); //产品代码
		params.put("OrgCode", loanConfig.getOrgCode()); //机构代码
		
		params.put("MobileNo", smsLog.getPhone()); //手机号码
		params.put("SendType", "TXT"); //短信类型
		params.put("SmsCode", templeteCode); //短信模板
		params.put("ReqParam", smsLog.getMsg()+"|"+ProductEnum.P_300002.getProductName()+"|"+smsVfCode); //参数配置
		
		logger.info("SmsController/sendSms =========LN1014短信发送接口========= url:{},param:{}", sendSmsUrl,params);
		JSONObject result = restTemplate.postForObject(sendSmsUrl, params, JSONObject.class);
		logger.info("SmsController/sendSms =========LN1014短信发送接口========= result:{}", result);
		
		BasicResp res = new BasicResp();
		if(result.isEmpty()){
			res.setCode(ServiceEnum.SERVICE_FAIL.getCode());
			res.setMessage(ServiceEnum.SERVICE_FAIL.getDesc());
			return res;
		}else if(LoanEnum.SUCCESS.getCode().equals(result.getString("RetCode"))){
			String key = ResidsConstant.SMS_PHONE_CODE+smsLog.getPhone();
			if(redisUtils.exists(key)){
				redisUtils.remove(key);
			}
			redisUtils.set(key, smsVfCode, smsExpires);
		}
		
        smsLog.setMsg(result.get("RetMsg")==null?"":result.get("RetMsg").toString());
        smsLog.setSmsCode(result.getString("RetCode"));
        smsLogMapper.insertSelective(smsLog);
        
		return BasicResp.back(result.getString("RetCode"), result.get("RetMsg"));
	}

	@Override
	public List<SmsLog> getPhoneHistory(SmsLog smsLog) {
		return null;
	}

	@Override
	@RequestMapping(value = "/checkSmsMsg" , method = RequestMethod.POST)
	public BasicResp checkSmsMsg(@RequestBody SmsLog smsLog) {
		String key = ResidsConstant.SMS_PHONE_CODE+smsLog.getPhone();
		Object value = redisUtils.get(key);
		logger.info("smsCode redis is "+ value+", smsCode is "+smsLog.getSmsCode()+",default smsCode is "+defaultSmsCode);
		if(null==value){
			return BasicResp.back(ServiceEnum.SMS_NOT_EXIST.getCode(), ServiceEnum.SMS_NOT_EXIST.getDesc());
		}else if(defaultSmsCode!=null&&defaultSmsCode.equals(smsLog.getSmsCode())){
			redisUtils.remove(key);
			return BasicResp.success();
		}else if(!smsLog.getSmsCode().equals(value)){
			return BasicResp.back(ServiceEnum.SMS_NOT_CORRECT.getCode(), ServiceEnum.SMS_NOT_CORRECT.getDesc());
		}
		redisUtils.remove(key);
		return BasicResp.success();
	}

}
